from PyQt4 import QtCore
from md5thread import MD5Thread
import os,sys, md5, bz2

class QPyShare_Share(QtCore.QObject):
    
    mode_Upload = 0
    mode_Download = 1
    
    status_NonStarted = 0
    status_Running = 1
    status_Paused = 2
    status_Finished = 3
    
    preview_Image = 0
    preview_Text = 1
    preview_None = 2
    
    def __init__(self, id, filename, fullFilename, size, mode):
        QtCore.QObject.__init__(self, None)
        
        self.id = id
        self.filename = filename
        self.fullFilename = fullFilename
        self.size = size
        self.mode = mode
        self.status = self.status_NonStarted
        self.transferred = 0
        self.transferredPercent = 0
        
        self.fileOK = True #false on download until finished downloading and md5sum ok
        
        self.previewType = self.preview_None
        self.preview = None
        
        self.fileH = QtCore.QFile(fullFilename)
        
        self.md5t = None #MD5check thread
        
        self.speed = 0
        self.speed_trans = 0
        self.timer = QtCore.QTimer()
        self.timer.setInterval(500)
        self.speedvar = (self.timer.interval()/1000.0)
        self.speed_count = self.speedvar
        
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.estimateSpeed)
        
    def openFile(self):
        
        if self.mode == self.mode_Upload:
            self.fileH.open(QtCore.QIODevice.ReadOnly)
        else:
            self.fileH.open(QtCore.QIODevice.WriteOnly)
            
    def isOpen(self):
        return self.fileH.isOpen()
    
    def readData(self,dataLen):
        
        data = self.fileH.read(dataLen)
        return data
    
    def writeData(self,data):
        
        self.fileH.write(data)
    
    def addTransferred(self,size):
        self.transferred = self.transferred + size
        
    def closeFile(self):
        self.fileH.flush()
        self.fileH.close()

    def setAsRunning(self):
        self.status = self.status_Running
        self.timer.start()
        
    def setAsFinished(self):
        self.speed = 0
        self.status = self.status_Finished
        self.timer.stop()
    
    def setAsPaused(self):
        self.speed = 0
        self.status = self.status_Paused
        self.timer.stop()
        
    def estimateSpeed(self):
        #estimate speed algorithm ??

        if (self.transferred - self.speed_trans) == 0:
            #print "jo"
            self.speed_count = self.speed_count + self.speedvar
            #print "speed a la que vengo", self.speed
            #print "cantidad de segundos sin que pase nada", self.speed_count
            #print "speed actual", self.speed
        else:
            #print "hay dif!"
            #if self.speed_count > self.speedvar:
                
            #else:
            #    self.speed = ((self.transferred - self.speed_trans) + self.speed) / 2.0
            self.speed = (((self.transferred - self.speed_trans)/self.speed_count) + self.speed) / 2
            self.speed_count = self.speedvar
            self.speed_trans = self.transferred
            #self.speed = (self.transferred - self.speed_trans)/self.speed_count
            
    def speedToText(self):
        return "%.2f KB/s" % (self.speed/1024.0)
    
    def statusToText(self):
        if self.status == self.status_NonStarted:
            text = QtCore.QCoreApplication.translate("QPyShare_Share","Non Started")
        elif self.status == self.status_Running:
            text = QtCore.QCoreApplication.translate("QPyShare_Share","Running")
        elif self.status == self.status_Paused:
            text = QtCore.QCoreApplication.translate("QPyShare_Share","Paused")
        elif self.status == self.status_Finished:
            text = QtCore.QCoreApplication.translate("QPyShare_Share","Finished")
        return text
        
    def sizeToText(self):
        text = str(self.size/1024) + " Kb"
        if self.size > (1024*1024) :
          text = "%.2f Mb (%s) "  % (self.size/(1024.0*1024.0),text)
        return text
        
    def transferredToText(self):
        return str(self.transferred/1024) + " Kb"
    
    def transferredPercentToText(self):
        return str((self.transferred*100) / self.size)
    
    def canStartSend(self):
        return self.status == self.status_NonStarted
    def canPause(self):
        return self.status == self.status_Running
    def canResume(self):
        return self.status == self.status_Paused
    def canOpenRun(self):
        if self.mode == self.mode_Upload:
            return True
        else:
            return self.status == self.status_Finished
        
    #def generateID(self):
    #   generateMD5()
    
    def checkMD5(self):
        self.md5t = MD5Thread()
        self.connect(self.md5t, QtCore.SIGNAL("finished()"), self.checkMD5_finished)
        self.md5t.filename = self.fullFilename
        self.md5t.start()
        
    def checkMD5_finished(self):
        md5 = self.md5t.id
        self.fileOK = (md5 == self.id)
        self.emit(QtCore.SIGNAL("md5check_finished(PyQt_PyObject)"), self)
        
    def setPreview(self, previewType, preview):
        self.previewType = previewType
        self.preview = preview
        
    def generatePreview(self):
        
        if self.mode == self.mode_Upload:
            
            fileinfo = QtCore.QFileInfo(self.fullFilename)
        
            previewType = self.preview_None
            preview = QtCore.QByteArray()
            
            graphicExtensions = ["bmp","jpg","jpeg","png","gif","xpm"]
            textExtensions = ["txt","xml","html"]
            
            ext = str(fileinfo.suffix().toLower().toLocal8Bit())
    
            if ext in graphicExtensions:
                
                from PyQt4 import QtGui
                image = QtGui.QImage(self.fullFilename)
                
                #valid img ?
                if not image.format() == QtGui.QImage.Format_Invalid:
                    
                    image = image.scaledToWidth(150,QtCore.Qt.SmoothTransformation)
                
                    buffer = QtCore.QBuffer(preview)
                    buffer.open(QtCore.QIODevice.WriteOnly)
                    image.save(buffer,"JPG",60)
                    buffer.close()
                    
                    previewType = self.preview_Image
            
            elif ext in textExtensions:
                
                previewType = self.preview_Text
                f = QtCore.QFile(self.fullFilename)
                f.open(QtCore.QIODevice.ReadOnly)
                preview = f.read(200)


            self.setPreview(previewType, preview)